<template>
  <div id="waitList">
    <div class="waitList-main">
      <div class="content">
        <div class="head">
          <span style="margin-right: 20px">
            相册:
            <el-select v-model="upload.GroupID" placeholder="相册" @change="changeAlbum">
              <el-option v-for="(v, k) in upload.albums" :key="k" :label="v.GroupName" :value="v.GroupID"></el-option>
              <el-option label="+添加相册" value="add"></el-option>
            </el-select>
          </span>
        </div>
        <div class="upload" v-if="upload.previewList.length == 0">
          <el-upload v-model:file-list="upload.fileList" action="" :show-file-list="false" accept=".png,.jpg,.jpeg" drag
            multiple style="
              display: flex;
              align-items: center;
              flex-direction: column;
              justify-content: center;
            " :http-request="uploadFiles">
            <div style="width: 100%">
              <div class="el-upload__text">
                <img src="@/assets/import.png" style="width: 200px; height: 200px" alt="" />
              </div>
              <el-button color="#000">选择图片</el-button>
            </div>
          </el-upload>
        </div>
        <div class="wapper" v-else>
          <div class="left">
            <div class="upload">
              <el-upload v-model:file-list="upload.fileList" class="upload-demo" action="" :show-file-list="false"
                accept=".png,.jpg,.jpeg" multiple :http-request="uploadFiles">
                <div class="item">
                  <el-icon :size="36" color="var(--theme-color)" style="vertical-align: middle">
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
            <div class="item" v-for="(v, k) in upload.previewList" :key="k" @click="choseImg(v)">
              <div class="close" @click.stop="del(v)">
                <el-icon color="red" :size="20">
                  <CircleCloseFilled />
                </el-icon>
              </div>
              <img :src="v.url" alt="" />
            </div>
          </div>
          <div class="card">
            <div class="box" v-if="upload.current.url">
              <div class="left">
                <el-image style="width: 100%; height: 100%; border-radius: 20px" :src="upload.current.url"
                  preview-teleported fit="cover" :preview-src-list="[upload.current.url]"></el-image>
              </div>
              <div class="right">
                <div class="top">
                  <div class="item">
                    <div class="label">标题</div>
                    <div class="form">
                      <el-input v-model="upload.current.formJson.PictureName"></el-input>
                    </div>
                  </div>
                  <div class="item">
                    <div class="label">主题</div>
                    <div class="form">
                      <el-select v-model="upload.current.formJson.ThemeID">
                        <el-option v-for="(v, k) in upload.themes" :key="k" :label="v.ThemeName"
                          :value="v.ThemeID"></el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
                <div class="auto">
                  <div class="label">智能标签</div>
                  <div class="form">
                    <el-tag class="tagitem" closable @close="delAutoTag(upload.current, s)" v-for="(
                        s, j
                      ) in upload.current.formJson.IntellectualTag.split(',')" :key="j" plain>
                      {{ s }}
                    </el-tag>
                  </div>
                </div>
                <div class="diy">
                  <div class="label">自定义标签</div>
                  <div class="form">
                    <div class="tags">
                      <template v-if="upload.current.formJson.CustomizingTag.length > 0">
                        <el-tag class="tagitem" v-for="(
                            s, j
                          ) in upload.current.formJson.CustomizingTag.split(
                            ','
                          )" :key="j" plain type="default" size="medium" closable round
                          @close="delTag(upload.current, s)">{{ s }}</el-tag>
                      </template>
                      <el-button style="margin: 0 10px" size="medium" circle type="default"
                        @click="addTag(upload.current)">
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </el-button>
                      <el-input style="width: 200px" v-model="tagInput" v-if="upload.current.showInput"
                        @blur="tagBlur($event, upload.current)"></el-input>
                    </div>
                  </div>
                </div>
                <div class="address">
                  <div class="label">位置 <span style="color:red"> * </span></div>
                  <div class="form">
                    <el-input v-model="upload.current.formJson.Address"></el-input>
                  </div>
                </div>
                <div class="desc">
                  <div class="label">描述 </div>
                  <div class="form">
                    <el-input type="textarea" v-model="upload.current.formJson.Desciption"></el-input>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="list">
          <div class="card" v-for="(v, k) in upload.previewList" :key="k">
            <div class="left">
              <el-button circle type="danger" @click="del(v)">
                <el-icon><DeleteFilled /></el-icon>
              </el-button>
              <el-image
                class="img"
                :src="v.url"
                preview-teleported
                :preview-src-list="[v.url]"
              ></el-image>
            </div>
            <div class="right">
              <el-form label-width="100px">
                <el-row>
                  <el-col :span="11">
                    <el-form-item label="图片名称">
                      <el-input v-model="v.formJson.PictureName"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :offset="1" :span="11">
                    <el-form-item label="图片主题">
                      <el-select v-model="v.formJson.ThemeID">
                        <el-option
                          v-for="(v, k) in upload.themes"
                          :key="k"
                          :label="v.ThemeName"
                          :value="v.ThemeID"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="智能标签">
                  <template v-if="v.formJson.IntellectualTag.length > 0">
                    <el-tag
                      v-for="(s, j) in v.formJson.IntellectualTag.split(',')"
                      :key="j"
                      plain
                      >{{ s }}</el-tag
                    >
                  </template>
                </el-form-item>
                <el-form-item label="自定义标签">
                  <div class="tags">
                    <template v-if="v.formJson.CustomizingTag.length > 0">
                      <el-tag
                        v-for="(s, j) in v.formJson.CustomizingTag.split(',')"
                        :key="j"
                        plain
                        closable
                        @close="delTag(v, s)"
                        >{{ s }}</el-tag
                      >
                    </template>
                    <el-button
                      style="margin: 0 10px"
                      size="small"
                      circle
                      type="primary"
                      @click="addTag(v)"
                    >
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </el-button>
                    <el-input
                      v-model="tagInput"
                      v-if="v.showInput"
                      @blur="tagBlur($event, v)"
                    ></el-input>
                  </div>
                </el-form-item>
                <el-form-item label="描述">
                  <el-input
                    type="textarea"
                    v-model="v.formJson.Desciption"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div> -->
        <!-- <div class="footer">
          <el-button type="primary" :loading="upload.loading" @click="submit"
            >提交图片</el-button
          >
        </div> -->
      </div>
    </div>
    <div class="footer">
      <template v-if="upload.previewList.length != 0">
        <div class="left">已上传{{ upload.previewList.length }}张图片</div>
        <div class="right">
          <el-button class="btn" @click="submit">提交内容</el-button>
        </div>
      </template>
      <template v-else>
        <div class="text" style="display:flex;width:100%;justify-content: space-between;">
          <div class="text-item">高品质照片和视频</div>
          <div class="text-item">文旅主题</div>
          <div class="text-item">版权权利</div>
          <div class="text-item">排除违规</div>
          <div class="text-item">申请下载使用</div>
        </div>
      </template>
    </div>
    <el-dialog v-model="upload.showAdd" title="新增相册" width="30%" draggable>
      <el-form :model="upload.formData" label-width="100">
        <el-form-item label="相册名称" porp="GroupName">
          <el-input v-model="upload.formData.GroupName" placeholder="相册名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="upload.showAdd = false">取消</el-button>
          <el-button type="primary" @click="addAlbum()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { nextTick, onMounted, onUnmounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import * as UploadApi from "@/api/upload";
import * as AlbumApi from "@/api/album";
import * as HomeApi from "@/api/home";
import { storeUser } from "@/store/user";
import HomeTitle from "@/components/title.vue";
import moment from "moment";
import { ElNotification } from "element-plus";
function getBase64Image(file) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise((res) => {
    reader.onload = function () {
      res(reader.result);
    };
  });
}
export default {
  name: "",
  components: {
    HomeTitle,
  },
  setup(props, ctx) {
    const loading = ref(false);
    const user = storeUser();
    const router = useRouter();
    const route = useRoute();
    const upload = reactive({
      loading: false,
      themes: [],
      fileList: [],
      previewList: [],
      albums: [],
      GroupID: "",
      custom: [],
      current: {},
      showAdd: false,
      formData: {
        GroupName: "",
      },
    });
    const tagInput = ref("");
    const getAlbum = async () => {
      let { data } = await AlbumApi.getList({
        UserAccount: user.UserAccount,
        PageSize: 999,
        PageIndex: 1,
      });
      if (data.UserData.list.length != 0) {
        upload.albums = data.UserData.list;
      } else {
        upload.albums = [{ GroupName: "默认相册", GroupID: 0 }];
      }
    };

    const getTheme = async () => {
      let { data } = await HomeApi.getTheme();
      if (data.Status != 0) return;
      upload.themes = data.UserData;
    };
    onMounted(() => {
      getAlbum();
      getTheme();
      if (route.query.GroupID) {
        nextTick(() => {
          upload.GroupID = Number(route.query.GroupID);
        });
      }
    });
    const getSize = (v) => {
      if (v < 1024) {
        return v + "b";
      } else if (v > 1024 && v < 1024 * 1024) {
        return (v / 1024).toFixed(2) + "kb";
      } else if (v > 1024 * 1024) {
        return (v / 1024 / 1024).toFixed(2) + "m";
      }
    };
    const compressImg = (file) => {
      let disposeFile = file;
      if (Object.prototype.toString.call(file) === "[object Blob]") {
        disposeFile = new File([file], file.name, { type: file.type });
      }
      const read = new FileReader();
      const fileSize = parseFloat(
        parseInt(disposeFile["size"]) / 1024 / 1024
      ).toFixed(2);
      // 小于1m不压缩
      if (fileSize < 4) return file;
      read.readAsDataURL(disposeFile);

      return new Promise((resolve, reject) => {
        try {
          read.onload = (e) => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = function () {
              let w = Math.floor(this.width / 2),
                h = Math.floor(this.height / 2);
              const canvas = document.createElement("canvas");
              const ctx = canvas.getContext("2d");
              let base64;
              canvas.setAttribute("width", w);
              canvas.setAttribute("height", h);
              ctx.drawImage(this, 0, 0, w, h);
              if (fileSize < 4) {
                // 如果图片小于一兆 那么不执行压缩操作
                base64 = canvas.toDataURL(disposeFile["type"], 1);
              } else {
                base64 = canvas.toDataURL(disposeFile["type"], 0.92);
              }
              console.log(base64);
              resolve(dataURLtoFile(base64, disposeFile.name));
            };
          };
        } catch (error) {
          reject(disposeFile);
        }
      });
    };
    const dataURLtoFile = (dataurl, fileName) => {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, {
        type: mime,
      });
    };
    const uploadFiles = async (v) => {
      // for (let i = 0; i < upload.fileList.length; i++) {
      // let x = upload.fileList[i];
      let file = await compressImg(v.file);
      let url = await getBase64Image(file);
      try {
        if (upload.previewList.findIndex((s) => s.uid == v.uid) == -1) {
          let { data: tag } = await UploadApi.getTags({ picbase64: url });
          if (tag.Status != 0) {
            upload.fileList.splice(i, 1);
            // continue;
            return
          }
          let res = {
            url,
            ...v.file,
            showInput: false,
            formJson: {
              UploadUserId: user.UserId,
              PictureName: v.file.name, //图片名称
              ThemeID: 1, //主题id
              IntellectualTag: tag.UserData, //智能标签
              CustomizingTag: "", //自定义标签
              Desciption: "", //图片描述
              Pixel: "", //像素
              OriginalFileLength: v.file.size, //图片大小
              FileName: v.file.name, //图片文件名
              Address: "绵阳",
            },
          };
          upload.previewList.push(res);
          upload.current = res;
        }
      } catch (error) {
        ElNotification({
          type: "error",
          title: "上传",
          message: "上传失败！",
        });
        // upload.fileList.splice(upload.fileList.length -1 ,1)
      }
      // }
    };
    const del = (v) => {
      let i = upload.previewList.findIndex((s) => s.uid == v.uid);
      if (i > -1) {
        upload.previewList.splice(i, 1);
        upload.fileList.splice(i, 1);
        upload.current = {};
      }
    };
    const addTag = (v) => {
      tagInput.value = "";
      let i = upload.previewList.findIndex((s) => s.uid == v.uid);
      upload.previewList[i].showInput = true;
    };
    const tagBlur = (e, v) => {
      if (tagInput.value.length > 20) {
        ElNotification({
          type: "error",
          title: "标签",
          message: "标签名过长",
        });
        return;
      }
      let i = upload.previewList.findIndex((s) => s.uid == v.uid);
      upload.previewList[i].showInput = false;
      if (!upload.previewList[i].formJson.CustomizingTag) {
        upload.previewList[i].formJson.CustomizingTag += tagInput.value;
      } else {
        upload.previewList[i].formJson.CustomizingTag += "," + tagInput.value;
      }
    };
    const delTag = (v, s) => {
      let i = upload.previewList.findIndex((s) => s.uid == v.uid);
      let arr = upload.previewList[i].formJson.CustomizingTag.split(",");
      let j = arr.findIndex((a) => a == s);
      arr.splice(j, 1);
      upload.previewList[i].formJson.CustomizingTag = arr.join(",");
    };
    const delAutoTag = (v, s) => {
      let i = upload.previewList.findIndex((s) => s.uid == v.uid);
      let arr = upload.previewList[i].formJson.IntellectualTag.split(",");
      let j = arr.findIndex((a) => a == s);
      arr.splice(j, 1);
      upload.previewList[i].formJson.IntellectualTag = arr.join(",");
    };
    const submit = async () => {
      if (upload.fileList == 0) {
        ElNotification({
          type: "error",
          title: "提交",
          message: "请先上传照片",
        });
        return;
      }
      for (let x of upload.previewList) {
        if (!x.formJson.Address) {
          ElNotification({
            type: 'error',
            title: '位置',
            message: "位置信息必须填写！"
          })
          return
        }
      }
      let PicturesJson = JSON.stringify({
        GroupID: upload.GroupID || 0,
        PictureList: upload.previewList.map((v) => v.formJson),
      });
      let filelist = upload.fileList.map((v) => v.raw);
      upload.loading = true;
      let { data } = await UploadApi.upload(
        {
          PicturesJson,
        },
        filelist
      );
      upload.loading = false;
      if (data.Status != 0) return;
      ElNotification({
        type: "success",
        title: "上传",
        message: "上传成功!",
      });
      router.push("/manage/album");
    };
    const choseImg = (v) => {
      upload.current = v;
    };
    const changeAlbum = (v) => {
      if (v == "add") {
        upload.GroupID = "";
        upload.formData.GroupName = "";
        upload.showAdd = true;
      }
    };
    const addAlbum = async () => {
      let { data } = await AlbumApi.add({
        UserAccount: user.UserAccount,
        GroupName: upload.formData.GroupName,
      });

      if (data.Status != 0) return;
      ElNotification({
        type: "success",
        message: "创建成功！",
        title: "创建相册",
      });
      upload.showAdd = false;
      getAlbum();
    };
    return {
      addAlbum,
      changeAlbum,
      upload,
      loading,
      moment,
      getSize,
      del,
      uploadFiles,
      addTag,
      tagBlur,
      delTag,
      delAutoTag,
      tagInput,
      submit,
      choseImg,
    };
  },
};
</script>

<style scoped lang="scss">
::v-deep(.el-table) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-table tr) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-table__cell) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-form-item__label) {
  // color: #fff !important;
}

::v-deep(.el-form-item) {
  display: flex;
  align-items: center;
  // color: #fff !important;
}

::v-deep(.el-textarea__inner) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-input__wrapper) {
  background: transparent !important;
  color: #fff !important;
  border: none;
  box-shadow: 0 0 0 !important;
}
::v-deep(.el-textarea__inner) {
  background: transparent !important;
  color: #000 !important;
  border: none;
  box-shadow: 0 0 0 !important;
  resize: none;
}
::v-deep(.el-textarea) {
  color: #fff !important;
  background: #fff;
  border-radius: 20px;
  padding: 10px 20px;
}

::v-deep(.el-table) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-table tr) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-table__cell) {
  background: transparent !important;
  color: #fff !important;
}

::v-deep(.el-input__inner) {
  // background: transparent !important;
  color: #000 !important;
  background: #fff;
  border: none;
}

::v-deep(.el-input) {
  // background: transparent !important;
  color: #fff !important;
  background: #fff;
  border-radius: 20px;
  padding: 10px 20px;
}

::v-deep(.el-table__body-wrapper) {
  height: 100%;
}

::v-deep(.el-table__inner-wrapper) {
  height: 100%;
}

::v-deep(.is-drag) {
  width: 100%;
}

.upload-drag {
  width: 100%;
  border: 1px dotted #ccc;
}

#waitList {
  position: relative;
  width: 100%;
  height: calc(100vh - 230px);
  border-top-left-radius: 30px;
  overflow-y: auto;

  .waitList-main {
    width: 100%;
    height: 100%;
    padding: 30px 20px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .title {
      margin-bottom: 20px;
    }

    .content {
      flex: 1;
      margin: 0 auto;
      width: 74%;
      overflow: auto;
      display: flex;
      flex-direction: column;

      .head {
        display: flex;
      }

      // .list {
      //   margin: 10px 0;
      //   flex: 1;
      //   overflow-y: scroll;
      //   padding: 20px;
      //   .card {
      //     margin-bottom: 20px;
      //     padding: 20px;
      //     border: 1px solid #ccc;
      //     display: flex;
      //     border-radius: 10px;
      //     .left {
      //       display: flex;
      //       margin-right: 20px;
      //       align-items: center;
      //       .img {
      //         margin-left: 10px;
      //         width: 150px;
      //         height: 150px;
      //       }
      //     }
      //     .right {
      //       flex: 1;
      //     }
      //   }
      // }
      .wapper {
        display: flex;
        margin-top: 20px;
        flex: 1;

        .left {
          margin-right: 40px;
          height: 80%;
          padding: 0 20px;
          overflow-y: auto;

          .item {
            width: 100px;
            height: 100px;
            background: #e8e6e6;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 10px;

            border-radius: 10px;
            // overflow: hidden;
            cursor: pointer;
            position: relative;

            .close {
              position: absolute;
              right: -5px;
              top: -5px;
            }

            img {
              border-radius: 10px;
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
        }

        .card {
          flex: 1;
          height: 80%;
          padding: 20px 0;
          overflow: hidden;

          .box {
            border-radius: 20px;
            height: 100%;
            background: #e8e6e6;
            padding: 20px;
            display: flex;
            align-items: center;

            .left {
              width: 400px;
              height: 300px;
              overflow: hidden;
              border-radius: 20px;
              margin-right: 20px;

              img {
                width: 100%;
                // height: 100%;
                object-fit: contain;
              }
            }

            .right {
              flex: 1;
              padding: 40px 40px;

              .top {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .item {}
              }

              .tagitem {
                font-size: 18px;
                font-weight: bold;
                color: #23c79b;
                // line-height: 42px;
                margin-right: 8px;
                padding: 8px 8px !important;
                border-radius: 20px;
                height: auto !important;
                background: #fff !important;
              }

              .label {
                color: #4d4d4d;
                margin: 20px 0 10px;
              }

              .auto {
                .form {
                  display: flex;
                  flex-wrap: wrap;
                }
              }

              .diy {
                .form {
                  .tags {
                    display: flex;
                    flex-wrap: wrap;
                  }
                }
              }
            }
          }
        }
      }

      // .footer {
      //   // text-align: right;
      //   align-self: center;
      // }
    }
  }
}

.tags {
  display: flex;
  align-items: center;
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 140px;
  width: calc(100% - 420px);
  background: var(--theme-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 210px;
  color: #fff;

  .btn {
    padding: 8px 16px;
    border-radius: 10px;
    background: #000;
    color: #fff;
    outline: none;
    border: none;
    cursor: pointer;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

.text-item {
  flex: 1;
  text-align: center;
}
</style>
